<template>
  <!-- 实时监控 -->
  <div class="topContent">
    <a-button
      v-hasPermission="'monitoringAdd'"
      key="submit"
      type="primary"
      class="greenBtn"
      @click="handleAdd"
      >新增摄像头</a-button
    >
    <a-button
      v-hasPermission="'monitoringTeach'"
      key="submit"
      type="link"
      @click="handleTeach"
      >摄像头分组教程</a-button
    >
    <div class="cardBox">
      <a-row :gutter="12">
        <a-col :span="12" v-for="(item, index) in playerList" :key="index">
          <a-card shadow="always" class="mt15">
            <div class="handleBar">
              <a-range-picker
                v-model:value="item.timeRange"
                type="datetimerange"
                separator="到"
                size="small"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                show-time
                class="dayPicker"
              />
              <div class="btnList">
                <a-button
                  type="primary"
                  size="small"
                  @click="
                    getCameraPlayUrl(
                      item.id,
                      item.quality,
                      index,
                      item.timeRange
                    )
                  "
                  >查看</a-button
                >
                <a-button
                  size="small"
                  @click="getCameraPlayUrl(item.id, 1, index, item.timeRange)"
                  v-if="item.quality === 2"
                  v-hasPermission="'monitoringSwitch'"
                  >切换高清</a-button
                >
                <a-button
                  size="small"
                  @click="getCameraPlayUrl(item.id, 2, index, item.timeRange)"
                  v-if="item.quality === 1"
                  v-hasPermission="'monitoringSwitch'"
                  >切换流畅</a-button
                >
                <a-popconfirm
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="confirmReStart(item)"
                >
                  <template #title> 是否确认远程重启摄像头? </template>
                  <a-button
                    v-hasPermission="'monitoringRestart'"
                    size="small"
                    danger
                    >重启</a-button
                  >
                </a-popconfirm>
                <a-button
                  v-if="item.progress === 1"
                  type="primary"
                  size="small"
                  @click="handleEdit(item)"
                  v-hasPermission="'monitoringEdit'"
                  >编辑</a-button
                >
                <a-button
                  v-if="item.progress !== 1"
                  type="primary"
                  size="small"
                  @click="handleEdit(item, 'isContinue')"
                  >萤石云配置</a-button
                >
                <a-popconfirm
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="confirmDel(item)"
                >
                  <template #title> 是否确定删除? </template>
                  <a-button
                    v-hasPermission="'monitoringDelete'"
                    size="small"
                    danger
                    >删除</a-button
                  >
                </a-popconfirm>
              </div>
            </div>
            <div class="viedo">
              <player
                v-if="item.url && elCardBoxW"
                :playerId="`video${index}`"
                :videoUrl="item.url"
                :width="elCardBoxW - 40"
                :accessToken="accessToken"
                :height="600"
              />
            </div>
          </a-card>
        </a-col>
      </a-row>
      <div v-if="!playerList.length">暂无摄像头数据</div>
    </div>
  </div>

  <!-- 新增摄像头 -->
  <AddMonitor
    :addMonitorVisible="addMonitorVisible"
    :rowData="rowData"
    :isEdit="isEdit"
    :editType="editType"
    :stationInfo="stationInfo"
    :supplierList="supplierList"
    @update:addMonitorVisible="addMonitorVisible = $event"
    @refreshList="getCameraList"
  />
  <!-- 摄像头教程 -->
  <Teach
    :teachVisible="teachVisible"
    @update:teachVisible="teachVisible = $event"
  />
</template>
<script setup>
import AddMonitor from "./conpoments/addMonitor.vue";
import Teach from "./conpoments/teach.vue";
import Player from "@/views/conpoments/player.vue";
import secret from "@/utils/secret";
const router = useRouter();
const route = useRoute();
const $api = inject("$api");
const addMonitorVisible = ref(false);
const teachVisible = ref(false);
const rowData = ref({});
const isEdit = ref(false);
const props = defineProps({
  stationInfo: {
    type: Number,
  },
  supplierList: {
    type: Array,
  },
});
const accessToken = ref("");
const handleAdd = () => {
  isEdit.value = false;
  editType.value = "";
  if (!props.stationInfo?.id) {
    message.error("请选择厂商");
    return;
  }
  addMonitorVisible.value = true;
};
const handleTeach = () => {
  teachVisible.value = true;
};
const playerList = ref([]);
const editType = ref("");
const handleEdit = (data, type) => {
  if (type) {
    editType.value = "isContinue";
  } else {
    editType.value = "";
  }
  rowData.value = data;
  isEdit.value = true;
  addMonitorVisible.value = true;
};
const confirmDel = async (data) => {
  const res = await $api.cameraDel(data.id);
  if (res.code === 0) {
    message.success("删除成功");
    getCameraList();
  }
};
const confirmReStart = async (data) => {
  const res = await $api.cameraReStart({
    id: data.id,
  });
  if (res.code === 0) {
    message.success("重启成功");
  }
};
const getCameraList = async (ata) => {
  const res = await $api.cameraList({
    stationId: props.stationInfo.id,
  });
  if (res.code === 0 && !!res.data.length) {
    playerList.value = res.data;
    res.data.forEach((item, index) => {
      if (item?.errorMsg) {
        notification.open({
          message: "摄像头异常",
          description: () =>
            h("div", [
              `摄像头【${item.serialNo}】初始化异常！原因：${item.errorMsg}。`,
              h("br"), // 创建换行元素
              `请调整好后再点击【萤石云配置】按钮初始化`,
            ]),
          duration: null,
          class: "notification-custom-class",
        });
      }
      getCameraPlayUrl(item.id, 2, index, null);
    });
  } else {
    playerList.value = [];
  }
};
const getCameraPlayUrl = async (id, quality, index, timeRange) => {
  const params = {
    id,
    quality,
    startTime: timeRange?.[0],
    stopTime: timeRange?.[1],
  };
  playerList.value[index] = {
    ...playerList.value[index],
    quality,
  };
  const res = await $api.cameraPlayUrl(params);
  if (res.code === 0) {
    const data = secret.decrypt(res.data);
    playerList.value[index].url = JSON.parse(data).url;
  }
  await nextTick();
  setWidth();
};
const cameraGetToken = async (id) => {
  const res = await $api.cameraGetToken();
  if (res.code === 0) {
    const data = secret.decrypt(res.data);
    accessToken.value = data;
  }
};
let elCardBoxW = ref(null);
const setWidth = () => {
  elCardBoxW.value = document.getElementsByClassName("ant-card-body")[0]
    ? document.getElementsByClassName("ant-card")[0].clientWidth
    : 560;
};
onBeforeUnmount(() => {
  // 退出时清除路由参数
  router.replace({ path: route.path, query: {} });
});
const handleChageStation = () => {
  notification.destroy();
  cameraGetToken();
  getCameraList();
  setTimeout(() => {
    setWidth();
  }, 500);
};
defineExpose({ handleChageStation });
</script>

<style lang="less" scoped>
.cardBox {
  margin-top: 20px;
}
.dayPicker {
  margin: 0 10px 10px 0;
  width: 300px;
}
.btnList {
  display: inline-block;
  .ant-btn {
    margin: 0 10px 10px 0;
  }
}
::v-deep(.ant-row) {
  min-width: 1400px;
}
.viedo {
  text-align: center;
}
::v-deep(.ant-card-body) {
  padding: 12px;
}
::v-deep(.notification-custom-class) {
  .ant-notification-notice-message {
    color: red;
  }
}
::v-deep(.ant-notification-notice-message) {
  color: red;
}
</style>
<style lang="less">
.notification-custom-class {
  width: 420px;
  .ant-notification-notice-message {
    color: red;
  }
}
</style>